package com.piece.core.authentication.handler;

import com.piece.core.framework.constant.CookieConstants;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.web.cookie.CookieUtil;
import com.piece.core.web.util.AuthenticationUtil;
import com.piece.core.web.util.ServletUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String username = AuthenticationUtil.getInstance(request).extractLoginName();

        //清空Session
        CookieUtil.deleteCookie(request, response, CookieConstants.SESSION_KEY);
        CookieUtil.deleteCookie(request, response, CookieConstants.TENANT_KET);
        AuthenticationUtil.getInstance(request).loginFailureLog(username, exception.getMessage());

        if (ServletUtil.isAjaxRequest(request)) {
            ServletUtil.renderString(response, JsonUtil.toJson(AjaxResponse.error(401, exception.getMessage())));
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}
